<template>
  <div class="container">
    <div class="sider">
      <div class="logo1">
        <img src="~@/assets/logo-spug-txt.png" alt="logo"/>
      </div>
      <div class="hosts">
        <a-spin :spinning="fetching">
          <a-input allowClear class="search" v-model="searchValue" placeholder="输入检索">
            <a-icon slot="prefix" type="search"/>
          </a-input>
          <a-directory-tree
            defaultExpandAll
            expandAction="dblclick"
            :icon='renderIcon'
            :treeData="searchTreeData()"
            @select="handleSelect">
          </a-directory-tree>
        </a-spin>
      </div>
    </div>
    <div class="content">
      <a-tabs
        hideAdd
        type="editable-card"
        v-model="activeId"
        @tabClick="setActiveId"
        @edit="handleRemove"
      >
        <a-button
          type="primary"
          v-if="activeId"
          style="margin-right: 5px"
          icon='folder-open'
          @click="handleOpenFileManager"
          slot="tabBarExtraContent">
          文件管理器
        </a-button>
        <a-tab-pane :key="item.vId" :tab="item.title" v-for="item in hosts">
          <Terminal :id="item.id" :vId="item.vId" :activeId="activeId"></Terminal>
        </a-tab-pane>
      </a-tabs>
      <pre class="fig" v-if="hosts.length ===0">{{ spug_web_terminal }}</pre>
    </div>
    <FileManager :id=hostId ref="FileManager"/>
  </div>
</template>

<script>
  import lds from 'lodash'
  import * as groupApi from '@/api/main/group'
  import Terminal from '@/views/system/ssh/Terminal'
  import FileManager from '@/views/system/ssh/FileManager'

  const spug_web_terminal =
    '                                                 __       __                          _                __\n' +
    '   _____ ____   __  __ ____ _   _      __ ___   / /_     / /_ ___   _____ ____ ___   (_)____   ____ _ / /\n' +
    '  / ___// __ \\ / / / // __ `/  | | /| / // _ \\ / __ \\   / __// _ \\ / ___// __ `__ \\ / // __ \\ / __ `// / \n' +
    ' (__  )/ /_/ // /_/ // /_/ /   | |/ |/ //  __// /_/ /  / /_ /  __// /   / / / / / // // / / // /_/ // /  \n' +
    '/____// .___/ \\__,_/ \\__, /    |__/|__/ \\___//_.___/   \\__/ \\___//_/   /_/ /_/ /_//_//_/ /_/ \\__,_//_/   \n' +
    '     /_/            /____/                                                                               \n'


  export default {
    name: 'SSH',
    components: {
      Terminal,
      FileManager
    },
    data() {
      return {
        spug_web_terminal,
        searchValue: '',
        fetching: false,
        activeId: '',
        treeData: [],
        hosts: [],
        hostId: ''
      }
    },
    created() {
      window.document.title = 'Web terminal'
      this.getTreeData()
      window.addEventListener('beforeunload', this.leaveTips)
    },
    watch: {},
    methods: {
      getTreeData() {
        groupApi.getList(Object.assign({ 'with_hosts': 1 })).then(res => {
          this.treeData = res.data.data
        })
      },
      searchTreeData() {
        if (this.searchValue) {
          return this.treeFilter(this.treeData, node => (node.hostname === this.searchValue || node.ip === this.searchValue))
        } return this.treeData
      },
      treeFilter(tree, func) {
        // 使用map复制一下节点，避免修改到原树
        return tree.map(node => ({ ...node })).filter(node => {
          node.children = node.children && this.treeFilter(node.children, func)
          return func(node) || (node.children && node.children.length)
        })
      },
      leaveTips(e) {
        e.returnValue = '确定要离开页面？'
      },
      renderIcon(node) {
        if (node.isLeaf) {
          return <a-icon type="cloud-server"/>
        } else if (node.expanded) {
          return <a-icon type="folder-open"/>
        } else {
          return <a-icon type="folder"/>
        }
      },
      setActiveId(id) {
        this.activeId = id
      },
      handleRemove(key, action) {
        if (action === 'remove') {
          const index = lds.findIndex(this.hosts, x => x.vId === key)
          if (index !== -1) {
            this.hosts.splice(index, 1)
            if (this.hosts.length > index) {
              this.setActiveId(this.hosts[index].vId)
            } else if (this.hosts.length) {
              this.setActiveId(this.hosts[index - 1].vId)
            } else {
              this.setActiveId(undefined)
            }
          }
        }
      },
      handleSelect(k, e) {
        if (e.nativeEvent.detail > 1 && e.node.isLeaf) {
          this._openNode(e.node)
        }
      },
      _openNode(node) {
        let data = { vId: String(new Date().getTime()), title: node.title, id: node.value }
        this.hosts.push(data)
        this.setActiveId(data.vId)
      },
      handleOpenFileManager() {
        const index = lds.findIndex(this.hosts, x => x.vId === this.activeId)
        if (index !== -1) {
          this.hostId = this.hosts[index].id
          this.$refs.FileManager.open()
        }
      }
    }
  }
</script>

<style lang="less">
  .container {
    display: flex;
    min-height: 100vh;

    .sider {
      display: flex;
      flex-direction: column;
      width: 280px;
      background-color: #fafafa;

      .logo1 {
        height: 42px;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #f0f0f0;

        img {
          height: 30px;
        }
      }

      .hosts {
        :global(.ant-tree-node-content-wrapper) {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        :global(.ant-tree) {
          background-color: #fafafa;
          height: calc(100vh - 98px);
          overflow: auto;
        }

        :global(.ant-tabs-bar) {
          margin: 0;
        }

        .search {
          margin: 12px 10px;
          width: 260px;
        }
      }
    }

    .content {
      flex: 1;
      display: flex;
      flex-direction: column;

      :global(.ant-tabs-nav) {
        width: calc(100vw - 280px);
        height: 42px;
        margin: 0;
      }

      .ant-tabs-bar {
        margin: 0;
      }

      :global(.ant-tabs-tab-active) {
        border-bottom: 2px solid #1890ff !important;
        transition: unset;
      }
    }
  }

  .terminal {
    flex: 1;
    display: flex;
    background-color: #000;
    padding-left: 5px;
    height: calc(100vh - 42px);
  }

  .fig {
    flex: 1;
    background-color: #000;
    color: #fff;
    padding-top: 200px;
    margin-bottom: 0;
    text-align: center;
  }

  .fileSize {
    padding-right: 24px !important;
  }

  .drawerHeader {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
  }

</style>